/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    vector<int> nextLargerNodes(ListNode *head)
    {
        vector<int> nums;
        while (head != nullptr)
        {
            nums.push_back(head->val);
            head = head->next;
        }
        int n = nums.size();
        vector<int> answer(n);
        stack<int> s;
        for (int i = n - 1; i >= 0; --i)
        {
            while (!s.empty())
            {
                if (s.top() <= nums[i])
                {
                    s.pop();
                }
                else
                {
                    break;
                }
            }
            if (s.empty())
            {
                answer[i] = 0;
            }
            else
            {
                answer[i] = s.top();
            }
            s.push(nums[i]);
        }
        return answer;
    }
};